package com.itheima.service.impl;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.PageQuery;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.User;
import com.itheima.pojo.UserLogin;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;


    //登录功能
    @Override
    public UserLogin login(User user) {
        // 1.查询用户
        User userInfo =  userMapper.login(user);
        //2.如果能查询到，则生成令牌
        if (userInfo!=null){
            //将第一个参数的属性值，复制给第二个参数
            UserLogin vo = new UserLogin();
            BeanUtils.copyProperties(userInfo,vo);
            //生成token令牌
            Map<String,Object> payload = new HashMap<>();
            payload.put("id",userInfo.getId());
            payload.put("username",userInfo.getUsername());
            payload.put("name",userInfo.getName());
            String token = JwtUtils.generateJwt(payload);
            vo.setToken(token);
            return vo;
        }
        //3.否则返回null
        return null;
    }


    //分页查询
    @Override
    public PageResult page(PageQuery<User> pageQuery) {
        //查询总数量
        Long total= userMapper.count(pageQuery.getT());
        //分页查询
        List<User> list = userMapper.list(pageQuery);
        long pages = total % pageQuery.getPageSize() == 0 ? total / pageQuery.getPageSize() : total / pageQuery.getPageSize();
        PageResult pageResult = PageResult.builder()
                .currentPage(pageQuery.getPage())
                .total(total)
                .pages((int) pages)
                .build();
        //集合数据
        pageResult.setData(list);
        return pageResult;
    }


}
